﻿using NHibernate;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyFrame
{
    /// <summary>
    /// Dal基类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class BaseDal<T> where T : BaseModel, new()
    {
        /// <summary>
        /// 表名(在派生类中赋值)
        /// </summary>
        protected string DbTableName = "";

        /// <summary>
        /// Session
        /// </summary>
        protected ISession CurrentSession = NHibernateHelper.NHibernateHelper.GetCurrentSession();

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="Id">主键</param>
        /// <returns></returns>
        public T Get(string Id)
        {
            //返回的是主键
            return (T)CurrentSession.Get(typeof(T), Id);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns>返回的是主键</returns>
        public string Add(T model)
        {
            string Id = CurrentSession.Save(model).ToString();
            CurrentSession.Flush();//使用Flush，Save之后可能没有保存
            return Id;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="Id">主键</param>
        public void Delete(string Id)
        {
            //其他属性无效
            T model = new T();
            model.Id = Id;
            CurrentSession.Delete(model);
            CurrentSession.Flush();
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="model"></param>
        public void Update(T model)
        {
            CurrentSession.Update(model);
            CurrentSession.Flush();
        }

        /// <summary>
        /// 获取全部
        /// </summary>
        /// <returns></returns>
        public List<T> GetAll()
        {
            IQuery query = CurrentSession.CreateQuery(string.Format("from {0}", DbTableName));
            return query.List<T>().ToList();
        }
    }
}
